# -*- coding: UTF-8 -*- 
from xml.etree import ElementTree as ET
import urllib2
from deal_info_api import *

def deal_info_url(f_xml, deal, url):
    deal_url = deal.getiterator(url)
    for node in deal_url:
	f_xml.write(('\t' * 2 + '<url><![CDATA[%s]]></url>\n' % (node.text)).encode('utf-8'))

def deal_city(tuan, city, city_id):
    (f_id, d_id, orig) = judge_begin(tuan, city)

    f_url = urllib2.urlopen('http://tuangou.ynet.com/index.php?m=API&a=goods&city=%s' % (city_id))

    root_url = ET.fromstring(f_url.read())

    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')

    f_xml.write('<deals>\n')

    deals = root_url.getiterator('goods')
    for deal in deals:
	if judge(f_id, d_id, deal, 'id'):
	    continue

	f_xml.write('\t' + '<deal>\n')
	deal_info_source(f_xml, 'ynet', '北青团购'.decode('utf-8'), 'http://tuangou.ynet.com/', 'http://tuangou.ynet.com/')
    	f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

	deal_info_add(f_xml, deal, 'id', 'id', 2)
	deal_info_add(f_xml, deal, 'title', 'name', 2)
	deal_info_cats(f_xml, deal, 'title')
	deal_info_vendor_2(f_xml,)
	deal_info_add(f_xml, deal, 'begintime', 'start_time', 2)
	deal_info_add(f_xml, deal, 'endtime', 'end_time', 2)
	deal_info_add(f_xml, deal, 'marketprice', 'o_price', 2)
	deal_info_add(f_xml, deal, 'groupprice', 'c_price', 2)
	deal_info_discount_and_save_money(f_xml, deal, 'groupprice', 'marketprice')
	deal_info_img(f_xml, deal, 'bigimg')
	deal_info_url(f_xml, deal, 'url')

	f_xml.write('\t' + '</deal>\n')

    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    judge_end(tuan, city)





city_list = open('%slist/citylist' % (get_home_dir()), 'r')
cities = eval(city_list.read())

f_city = urllib2.urlopen('http://tuangou.ynet.com/index.php?m=API&a=citys')
root_city = ET.fromstring(f_city.read())
city_id = root_city.getiterator('id')
city_name = root_city.getiterator('name')

for i in range(len(city_name)):
    try:
	deal_city('ynet', cities[city_name[i].text.encode('utf-8')], city_id[i].text)
    except KeyError:
	os.system(('date >> %serror.log && echo "%s KeyError: %s\n" >> %serror.log' % (get_home_dir(), 'ynet', city_name[i].text)).encode('utf-8'), get_home_dir())


